package com.usernet.product.web.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.usernet.product.comm.BaseAction;
import com.usernet.product.entity.Admin;
import com.usernet.product.entity.Type;
import com.usernet.product.tools.FileTools;
import com.usernet.product.utils.DateUtils;
import com.usernet.product.utils.LogConstants;
import com.usernet.product.utils.Page;
import com.usernet.product.utils.PageResult;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;
import com.usernet.product.utils.StringUtils;
import com.usernet.product.web.form.TypeForm;

public class TypeAction extends BaseAction {

	public ActionForward toList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		TypeForm mForm = (TypeForm) form;
		// 查询条件
		String name = mForm.getName();
		int flag = mForm.getFlag();

		PageResult<Type> result = null;
		Page page = new Page();
		// 分页信息
		String pageNo = mForm.getPageNo();
		String pageSize = mForm.getPageSize();
		if (pageSize != null) {
			page.setEveryPage(Integer.parseInt(pageSize.trim()));
		}
		if (pageNo != null) {
			page.setCurrentPage(Integer.parseInt(pageNo.trim()));
		}
		// 条件查询
		if (name != null || flag != -1) {
			// 有条件
			result = typeDao.getAllByParams(page, name, flag);
		} else {

			result = typeDao.getAllByPage(page);
		}
		request.setAttribute("form", mForm);
		request.setAttribute("list", result.getContent());
		request.setAttribute("page", result.getPage());
		request.setAttribute("size", result.getSize());

		return mapping.findForward("list");
	}

	public ActionForward toAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int count = typeDao.getCount();
		request.setAttribute("count", count);
		return mapping.findForward("add");
	}

	public ActionForward doAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		TypeForm mForm = (TypeForm) form;
		Type type = mForm.getType();
		FormFile file = mForm.getIcon();
		String name = file.getFileName();
		String fileType = name.substring(name.lastIndexOf("."), name.length());
		if (!".png".equals(fileType.toLowerCase())) {
			request.setAttribute("msg", "图片类型错误,必须为PNG");
			request.setAttribute("return", "type.do?method=toAdd");
			return mapping.findForward("admin_msg");
		} else {
			String realPath = ProductConfig.realPath + "upload\\icon\\"
					+ DateUtils.getDate() + "\\";
			// 创建文件
			FileTools.createDateFile(realPath);
			InputStream in = file.getInputStream();
			String fileName = StringUtils.getUUID();
			OutputStream out = new FileOutputStream(realPath + fileName);
			out.write(file.getFileData(), 0, file.getFileSize());
			in.close();
			in = null;
			out.close();
			out = null;
			type.setIcon(DateUtils.getDate() + "/" + fileName);
			type.setTime(new Timestamp(System.currentTimeMillis()));
			type.setStatus(0); // 状态为0，可用
			type.setPinyin(ProductUtils.getFullChars(type.getName()));// 拼音
			int id = typeDao.save(type);
			if (id > 0) {
				Admin admin = (Admin) request.getSession()
						.getAttribute("admin");
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.add_type, new Object[] { id,
								type.getName() }), null);
				return mapping.findForward("other");
			} else {
				request.setAttribute("msg", "添加失败");
				request.setAttribute("return", "type.do?method=toList");
				return mapping.findForward("admin_msg");
			}
		}
	}

	public ActionForward toUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int count = typeDao.getCount();
		request.setAttribute("count", count);
		int id = Integer.parseInt(request.getParameter("id"));
		Type type = (Type) typeDao.getById(Type.class, id);
		request.setAttribute("type", type);
		return mapping.findForward("update");
	}

	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String url = request.getParameter("url");
		request.setAttribute("url", url);

		return mapping.findForward("img");
	}

	public ActionForward doUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		TypeForm mForm = (TypeForm) form;
		Type type = mForm.getType();
		String oldIcon = type.getIcon();
		Type updateType = (Type) typeDao.getById(Type.class, type.getId());
		FormFile file = mForm.getIcon();
		if (file != null && file.getFileSize() > 0) {
			String name = file.getFileName();
			String fileType = name.substring(name.lastIndexOf("."), name
					.length());
			if (!".png".equals(fileType.toLowerCase())
					&& !".jpg".equals(fileType.toLowerCase())) {
				request.setAttribute("msg", "图片类型错误,必须为PNG");
				request.setAttribute("return", "type.do?method=toUpdate&id="
						+ type.getId());
				return mapping.findForward("admin_msg");
			} else {
				String realPath = ProductConfig.realPath + "upload\\icon\\"
						+ DateUtils.getDate() + "\\";
				// 创建文件
				FileTools.createDateFile(realPath);
				InputStream in = file.getInputStream();

				String fileName = StringUtils.getUUID();
				OutputStream out = new FileOutputStream(realPath + fileName);
				out.write(file.getFileData(), 0, file.getFileSize());
				in.close();
				in = null;
				out.close();
				out = null;
				updateType.setIcon(DateUtils.getDate() + "/" + fileName);
			}
		}
		updateType.setName(type.getName());
		updateType.setPinyin(ProductUtils.getFullChars(type.getName()));// 拼音
		updateType.setRemark(type.getRemark());
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		int sort = type.getSort();
		if (sort != updateType.getSort()) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.update_type_sort, new Object[] {
							sort,type.getId(), type.getName() }), null);
		}
		updateType.setPinyin(type.getPinyin());
		updateType.setSort(type.getSort());
		updateType.setFlag(type.getFlag());
		updateType.setPinyin(ProductUtils.getFullChars(type.getName()));// 拼音
		updateType.setTime(new Timestamp(System.currentTimeMillis()));
		if (typeDao.modify(updateType)) {
			// 删除原icon
			String filePath = ProductConfig.realPath + "upload\\icon\\"
					+ oldIcon;
			File oldFile = new File(filePath);
			if (oldFile.exists()) {
				oldFile.delete();
			}
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.update_type, new Object[] {
							type.getId(), type.getName() }), null);
			return mapping.findForward("other");
		} else {
			request.setAttribute("msg", "更新失败");
			request.setAttribute("return", "type.do?method=toList");
			return mapping.findForward("admin_msg");
		}

	}

	public ActionForward doDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Type type = (Type) typeDao.getById(Type.class, id);
		if (typeDao.delete(type)) {
			File file = new File(ProductConfig.realPath + "/upload/icon/"
					+ type.getIcon());
			if (file.isFile() && file.exists()) {
				file.delete();
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.delete_type, new Object[] {
							type.getId(), type.getName() }), null);
			return mapping.findForward("other");
		} else {
			request.setAttribute("msg", "删除失败");
			request.setAttribute("return", "type.do?method=toList");
			return mapping.findForward("admin_msg");
		}
	}

	/*
	 * 锁定
	 */
	public ActionForward doCancle(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Type type = (Type) typeDao.getById(Type.class, id);
		type.setStatus(1);// 不可用
		if (typeDao.modify(type)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.lock_type, new Object[] {
							type.getId(), type.getName() }), null);
		}
		return mapping.findForward("other");
	}

	/*
	 * 解锁
	 */
	public ActionForward doOk(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Type type = (Type) typeDao.getById(Type.class, id);
		type.setStatus(0);// 可用
		if (typeDao.modify(type)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.unlock_type, new Object[] {
							type.getId(), type.getName() }), null);
		}
		return mapping.findForward("other");
	}
}
